home *** CD-ROM | disk | FTP | other *** search
/ Nebula 1 / Nebula One.iso / Educational / PrimeSpiral / Source / PrimeGenerator.m < prev    next >
Encoding:
Text File  |  1995-06-12  |  1.4 KB  |  69 lines

  1. /* File:    PrimeGenerator.m - Prime generator for 'PrimeSpiral'
  2.  *
  3.  * By:        Christopher Lane
  4.  *        Symbolic Systems Resources Group
  5.  *        Knowledge Systems Laboratory
  6.  *        Stanford University
  7.  *
  8.  * Date:    24 February 1990
  9.  *
  10.  * Copyright:    1990 by The Leland Stanford Junior University.  This program
  11.  *        may be distributed without restriction for non-commercial use.
  12.  */
  13.  
  14. #import <stdlib.h>
  15. #import <stdio.h>
  16.  
  17. #import "PrimeGenerator.h"
  18.  
  19. @implementation PrimeGenerator
  20.  
  21. + new
  22. {
  23.     self = [super new];
  24.     
  25.     if ((primes = (ENTRY *) calloc((maximum = NUMELEMS), sizeof(ENTRY))) == NULL) {
  26.         perror("calloc");
  27.         exit(EXIT_FAILURE);
  28.         }
  29.         
  30.     index = 0;
  31.     number = 1;
  32.     
  33.     return self;
  34. }
  35.     
  36. - (unsigned int) generate
  37. {
  38.     register unsigned int i;
  39.     
  40.     if (number > 2) {
  41. loop:    for (i = 1, number += 2; i < index && number >= primes[i].square; i++)
  42.             if (number == primes[i].square || (number % primes[i].prime) == 0) goto loop;
  43.         }
  44.     else number++;
  45.     primes[index].prime = number;
  46.     primes[index].square = number * number;
  47.     if (++index == maximum) {
  48. #ifdef DEBUG
  49.         (void) printf("Maximum (%d) primes exceeded, resizing.\n", maximum);
  50. #endif
  51.         if ((primes = (ENTRY *) realloc((void *) primes, (maximum += NUMELEMS) * sizeof(ENTRY))) == NULL) {
  52.             perror("realloc");
  53.             exit(EXIT_FAILURE);
  54.             }
  55.         }
  56. #ifdef DEBUG
  57.     (void) printf("%d", number);
  58. #endif
  59.     return (number);
  60. }
  61.  
  62. - free
  63. {
  64.     if (primes != NULL) cfree((void *) primes);
  65.     return [super free];
  66. }
  67.  
  68. @end
  69.